<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Authentication\Result;
use Zend\Authentication\Storage\Session;
use Application\Auth\Adapter;
use Application\Auth\AuthenticationService;
use Application\Auth\SaltCellar;
use Zend\Session\Container;
use Application\Form\ConnexionForm;

class AuthController extends AbstractActionController
{
// 	protected $saltData = array(
// 			'years' => array(2011 => 'teg', 2012 => 'e', 2013 => 'qze'),
// 			'months' => array(1 => 'fsq', 2 => '02', 3 => 'q', 4 => 'gdsg', 5 => '(3339',
// 					6 => 'fdERs', 7 => 'FDS45$q', 8 => '[sxdi', 9 => 'Fdsdf', 10 => 'FDSDfeh', 11 => 'FDFDSFSDFSs',
// 					12 => 'FDSFDSF5423Q'
// 			),
// 			'days' => array(1 => 'vcxv', 2 => 'gfvc"', 3 => 'RG', 4 => 'FDSFvcxz', 5 => 'gfdgfg', 6 => 'vd', 7 => 'ret', 8 => 'dfs:', 9 => './DF./DSF',
// 					10 => 'flgdoh', 11 => 'cvxcryk', 12 => 'VVVv', 13 => 'tokykoh', 14 => 'fglfljutj', 15 => 'yujkh,', 16 => 'dnnbi', 17 => 'fdvb;mfdg', 18 => '_JS2---2UIne', 19 => 'fhopsdf', 20 => '43IT54IG9,nvb', 21 => '34594TK?GD',
// 					22 => 'jlhjlteyrt', 23 => 'Fdvbb,n', 24 => 'bvcgjytutuy', 25 => 'Fdbvcbv,nb,', 26 => 'ythgbdfgfdg', 27 => 'vcgfyty', 28 => 'Gdfsgfdg48', 29 => 'fdsgtree', 30 => 'fgpdtdpoytre99', 31 => 'FDSP04Rofgfdng'
// 			)
// 	);
	protected $fingerHash = array('start' => 'st$^ar', 'end' => 'tend');
	protected $model = array('login' => 'login', 'password' => 'password',
			'mail' => 'vail_admin', 'role' => 'role_admin', 'access' => 'access_admin'
	);
	protected $serializedCols = array('access');
	protected $defaultColumns = array('login' => 'login', 'password' => 'password');
	protected $modelColumns = array('login' => 'login', 'password' => 'password');
	/**
	 * Log user.
	*/
	public function loginAction()
	{
		// Set up the authentication adapter
		$authAdapter = new Adapter($this->getServiceLocator()->get("zenddbadapteradapter"), "lamisa_user", $this->defaultColumns['login'], $this->defaultColumns['password'], "is_active", 1);
		//$datas = $ConnexionForm->getData ();
		//$login = $datas ['login'];
		
		$request = $this->getRequest();
		
	
		//$authAdapter = new Adapter($this->getServiceLocator()->get('config'), "lamisa_user", $this->defaultColumns['login'], $this->defaultColumns['password'],"is_active", 1);
		$authAdapter->setSerializedCols($this->serializedCols);
		$authAdapter->setIdentity($request->getPost('login'));
		$authAdapter->setCredential($request->getPost('password'));
		//$authAdapter->setSaltCellar(new SaltCellar($this->saltData));
		$authAdapter->setModelArray($this->model);
		$authAdapter->setFingerHash($this->fingerHash);
		$authAdapter->setSessionTimeout(180); // 30 minutes
		// instantiate the authentication service
		$auth = new AuthenticationService();
		$auth->setStorage(new Session('front'));
		$auth->setModelArrayColumns($this->modelColumns);
		$result = $auth->authenticate($authAdapter);
		switch($result->getCode())
		{
			// identity doesn't exist
			case Result::FAILURE_IDENTITY_NOT_FOUND:
				echo "Identity not found";
				break;
				// invalid credentials
			case Result::FAILURE_CREDENTIAL_INVALID:
				echo "Credentials invalid";
				break;
				// OK
			case Result::SUCCESS:
				//echo "OK";
				break;
				// default action;
			default:
				echo "Default";
				break;
		}
		if($result->isValid())
		{
			
			//$session = new Zend_Session_Namespace( 'Zend_Auth' );
			$data = $authAdapter->getResultRowObject(array('nom','prenom','email'));
			$nom = $authAdapter->getResultRowObject(array('nom'));
			$prenom = $authAdapter->getResultRowObject(array('prenom'));
			$email = $authAdapter->getResultRowObject(array('email'));
			$login = $authAdapter->getResultRowObject(array('login'));
			$user_id = $authAdapter->getResultRowObject(array('id_user'));
			$is_admin = $authAdapter->getResultRowObject(array('is_admin'));
			$is_active = $authAdapter->getResultRowObject(array('is_active'));
			
			$auth->getStorage()->write($data);
			
			$user_session = new Container('user');
			$user_session->is_connected = 1;
			
		
			//print_r($login);
	
			foreach ($user_id as $row) {			
				$user_session->id_user = $row;				
			}
			
			foreach ($login as $row) {		   
				$user_session->login = $row;		  
			}

			foreach ($is_admin as $row) {
				$user_session->is_admin = $row;
			}
				
			foreach ($is_active as $row) {
					$user_session->is_active = $row;
			}
			
			foreach ($prenom as $row) {
				$user_session->prenom = $row;
			}
			foreach ($nom as $row) {
				$user_session->nom = $row;
			}
			foreach ($email as $row) {
				$user_session->mail = $row;
			}
				
			
// 			foreach ($prenom as $row) {		
// 				$user_session->prenom = $row;
// 			}
			
			//$timeLeftTillSessionExpires = $_SESSION['user'] - time();
			$user_session->setExpirationSeconds(900);
		
			//print_r($_SESSION);

		
		return $this->redirect ()->toRoute ( $_REQUEST['url2'] );
			
		//	print_r($_REQUEST['url2']);
//  			return $this->redirect ()->toRoute ( 'intranet', array (
//  					'controller' => 'Intranet',
//  					'action' => 'intranet',
//  					'user' =>$data,
//  			) );
			
			
		}
		else
		{
			echo "Logged incorrectly";
		}
		die();
	}
	/**
	 * Checks user by storage data.
	 */
	public function checkAction()
	{
		$authAdapter = new Adapter($this->getServiceLocator()->get("zenddbadapteradapter"), "lamisa_user", $this->defaultColumns['login'], $this->defaultColumns['password'], "SHA1(?)", "is_active", 1);
		$authAdapter->setSerializedCols($this->serializedCols);
		//$authAdapter->setSaltCellar(new SaltCellar($this->saltData));
		$authAdapter->setModelArray($this->model);
		$authAdapter->setFingerHash($this->fingerHash);
		$authAdapter->setSessionTimeout(1800);
		$auth = new AuthenticationService();
		$auth->setRegenerateId(true);
		$auth->setStorage(new Session('front'));
		$auth->setModelArrayColumns($this->modelColumns);
		$result = $auth->authenticate($authAdapter);
		$identity = $auth->getIdentity();
		
		if($auth->hasIdentity())
		{
			echo "has identity";
		}
		else
		{
			echo "hasn't identity";
		}
		die();
	}
}









/*
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Form\Annotation\AnnotationBuilder;
use Zend\View\Model\ViewModel;
 
use Application\Model\User;
 
class AuthController extends AbstractActionController
{
    protected $form;
    protected $storage;
    protected $authservice;
     
    public function getAuthService()
    {
        if (! $this->authservice) {
            $this->authservice = $this->getServiceLocator()
                                      ->get('AuthService');
        }
         
        return $this->authservice;
    }
     
    public function getSessionStorage()
    {
        if (! $this->storage) {
            $this->storage = $this->getServiceLocator()
                                  ->get('Application\Model\MyAuthStorage');
        }
         
        return $this->storage;
    }
     
    public function getForm()
    {
        if (! $this->form) {
            $user       = new User();
            $builder    = new AnnotationBuilder();
            $this->form = $builder->createForm($user);
        }
         
        return $this->form;
    }
     
    public function loginAction()
    {
        //if already login, redirect to success page
        if ($this->getAuthService()->hasIdentity()){
            return $this->redirect()->toRoute('success');
        }
                 
        $form       = $this->getForm();
         
        return array(
            'form'      => $form,
            'messages'  => $this->flashmessenger()->getMessages()
        );
    }
     
    public function authenticateAction()
    {
        $form       = $this->getForm();
        $redirect = 'login';
         
        $request = $this->getRequest();
        if ($request->isPost()){
            $form->setData($request->getPost());
            if ($form->isValid()){
                //check authentication...
                $this->getAuthService()->getAdapter()
                                       ->setIdentity($request->getPost('username'))
                                       ->setCredential($request->getPost('password'));
                                        
                $result = $this->getAuthService()->authenticate();
                foreach($result->getMessages() as $message)
                {
                    //save message temporary into flashmessenger
                    $this->flashmessenger()->addMessage($message);
                }
                 
                if ($result->isValid()) {
                    $redirect = 'success';
                    //check if it has rememberMe :
                    if ($request->getPost('rememberme') == 1 ) {
                        $this->getSessionStorage()
                             ->setRememberMe(1);
                        //set storage again
                        $this->getAuthService()->setStorage($this->getSessionStorage());
                    }
                    $this->getAuthService()->getStorage()->write($request->getPost('username'));
                }
            }
        }
         
        return $this->redirect()->toRoute($redirect);
    }
     
    public function logoutAction()
    {
        $this->getSessionStorage()->forgetMe();
        $this->getAuthService()->clearIdentity();
         
        $this->flashmessenger()->addMessage("You've been logged out");
        return $this->redirect()->toRoute('login');
    }
}
*/
?>